package com.itheima.search;

public class BlockSearch {
    public static void main(String[] args) {
        int[] arr={16,5,9,12,21,18,
                32,23,37,26,45,34,
                50,48,61,52,73,56};
        Block b1=new Block(21,0,5);
        Block b2=new Block(45,6,11);
        Block b3=new Block(73,12,17);
        Block[] blockArr={b1,b2,b3};
        int num=32;

        int index = getIndex(arr,blockArr,num);
        System.out.println(index);

    }

    private static int getIndex(int[] arr,Block[] blockArr, int num) {
        //1.先确定要查找的数据在哪一块当中
        int blockIndex = getBlockIndex(num, blockArr);
        if(blockIndex==-1){
            return -1;
        }
        //2.获取块对象
        Block b = blockArr[blockIndex];
        //3.获取块对象的起始索引和结束索引
        int startIndex = b.getStartIndex();
        int endIndex = b.getEndIndex();

        for (int i = startIndex; i <= endIndex; i++) {
            if (arr[i]==num){
                return i;
            }
        }
        return -1;

    }

    private static int getBlockIndex(int num, Block[] blockArr) {
        for (int i = 0; i < blockArr.length; i++) {
            if (num<=blockArr[i].getMax()){
                return i;
            }
        }
        return -1;
    }
}

class Block{
    private int max;
    private int startIndex;
    private int endIndex;


    public Block() {
    }

    public Block(int max, int startIndex, int endIndex) {
        this.max = max;
        this.startIndex = startIndex;
        this.endIndex = endIndex;
    }

    /**
     * 获取
     * @return max
     */
    public int getMax() {
        return max;
    }

    /**
     * 设置
     * @param max
     */
    public void setMax(int max) {
        this.max = max;
    }

    /**
     * 获取
     * @return startIndex
     */
    public int getStartIndex() {
        return startIndex;
    }

    /**
     * 设置
     * @param startIndex
     */
    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }

    /**
     * 获取
     * @return endIndex
     */
    public int getEndIndex() {
        return endIndex;
    }

    /**
     * 设置
     * @param endIndex
     */
    public void setEndIndex(int endIndex) {
        this.endIndex = endIndex;
    }

    public String toString() {
        return "Block{max = " + max + ", startIndex = " + startIndex + ", endIndex = " + endIndex + "}";
    }
}